package com.mobilelmes;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import Tools.MyExpandableAdapter;
import Tools.NavDrawerItem;
import Tools.NavDrawerListAdapter;
import Tools.TodoProvider;

public class Main extends Activity {
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private TypedArray navMenuIcons;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] mLeftSideBarTitles;
	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;
	FileOutputStream fout = null;
	BufferedOutputStream buffout = null;
	Button announ, calendar, todolist;
	Fragment fragment = null;
	private static ListView taskView;
	private static EditText etNewTask;
	private static TodoProvider provider;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getActionBar().hide(); 

		mTitle = mDrawerTitle = getTitle();

		// load slide menu items
		mLeftSideBarTitles = getResources().getStringArray(R.array.LeftSideBarArray);
		// nav drawer icons from resources
		navMenuIcons = getResources()
				.obtainTypedArray(R.array.LeftImageArray);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		navDrawerItems = new ArrayList<NavDrawerItem>();

		// adding nav drawer items to array
		// Home
		navDrawerItems.add(new NavDrawerItem(mLeftSideBarTitles[0], navMenuIcons.getResourceId(0, -1)));
		// Find People
		navDrawerItems.add(new NavDrawerItem(mLeftSideBarTitles[1], navMenuIcons.getResourceId(1, -1)));
		// Photos
		navDrawerItems.add(new NavDrawerItem(mLeftSideBarTitles[2], navMenuIcons.getResourceId(2, -1)));
		// Communities, Will add a counter here
		navDrawerItems.add(new NavDrawerItem(mLeftSideBarTitles[3], navMenuIcons.getResourceId(3, -1)));
		// Logout
		navDrawerItems.add(new NavDrawerItem(mLeftSideBarTitles[4], navMenuIcons.getResourceId(4, -1)));


		// Recycle the typed array
		navMenuIcons.recycle();

		// setting the nav drawer list adapter
		Log.d("Allen", "enter 98");
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		Log.d("Allen", "enter 101");
		
		mDrawerList.setAdapter(adapter);
		// enabling action bar app icon and behaving it as toggle button
		//        getActionBar().setDisplayHomeAsUpEnabled(true);
		//        getActionBar().setHomeButtonEnabled(true);
		// 
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_arrow, //nav menu toggle icon
				R.string.app_name, // nav drawer open - description for accessibility
				R.string.app_name // nav drawer close - description for accessibility
				){
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		//getActionBar().setDisplayShowTitleEnabled(false);
		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
		if (savedInstanceState == null) {
			displayView(0);
			//selectItem(0);
		}
		Log.d("Lo", "On Create Finished");
	}

	/**
	 * Slide menu item click listener
	 * */
	private class SlideMenuClickListener implements
	ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// display view for selected nav drawer item
			displayView(position);
			Log.d("Lo","listener");
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content view
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
		switch(item.getItemId()) {
		case R.id.action_settings:
			// create intent to perform web search for this planet
			Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
			intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
			// catch event that there's no activity to handle intent
			if (intent.resolveActivity(getPackageManager()) != null) {
				startActivity(intent);
			} else {
				Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
			}
			return true;
			/*case R.id.test:
			// create intent to perform web search for this planet
			Intent intent2 = new Intent(Intent.ACTION_WEB_SEARCH);
			intent2.putExtra(SearchManager.QUERY, getActionBar().getTitle());
			// catch event that there's no activity to handle intent
			if (intent2.resolveActivity(getPackageManager()) != null) {
				startActivity(intent2);
			} else {
				Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
			}
			return true;*/
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayView(int position) {

		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new AmtFragment();
			//fragment = new LeftFragment();
			//args = new Bundle();
			//args.putInt(LeftFragment.ARG_LEFT_ITEM, position);
			//fragment.setArguments(args);
			break;
		case 1:
			fragment = new CalFragment();
			//fragment = new LeftFragment();
			//args = new Bundle();
			//args.putInt(LeftFragment.ARG_LEFT_ITEM, position);
			//fragment.setArguments(args);
			break;
		case 2:
			fragment = new CFragment();
			//args = new Bundle();
			//args.putInt(LeftFragment.ARG_LEFT_ITEM, position);
			//fragment.setArguments(args);
			break;
		case 3:
			fragment = new TdlFragment();
			//			args = new Bundle();
			//			args.putInt(LeftFragment.ARG_LEFT_ITEM, position);
			//			fragment.setArguments(args);
			break;
		case 4:
			new AlertDialog.Builder(Main.this)
			.setTitle("Logout")
			.setMessage("Confirm Logout?")
			.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					mDrawerLayout.closeDrawer(mDrawerList);
				}
			})

			.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialoginterface, int i) {
					Intent intent=new Intent();
					intent.setClass(Main.this,Login.class);
					startActivity(intent);
				}
			})
			.show();
			break;

		default:
			break;
		}

		if (fragment != null) {
			Log.d("Lo", "Select start");
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
			.replace(R.id.content_frame, fragment).commit();

			// update selected item and title, then close the drawer
			mDrawerList.setItemChecked(position, true);
			//mDrawerList.setSelection(position);
			//setTitle(mLeftSideBarTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
			Log.d("Lo","Selected end");
		}
	}


	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}



	

	public static class AmtFragment extends Fragment {
		private ArrayList<String> parentItems = new ArrayList<String>();
		private ArrayList<Object> childItems = new ArrayList<Object>();
		private ArrayList<Object> childContent = new ArrayList<Object>();
		public AmtFragment() {
			// Empty constructor required for fragment subclasses
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_announ, container, false);
			
			try{
				ExpandableListView expandableList = (ExpandableListView) rootView.findViewById(R.id.announview);
				
				expandableList.setDividerHeight(2);
				expandableList.setGroupIndicator(null);
				expandableList.setClickable(true);

				setGroupParents();
				setChildData();

				MyExpandableAdapter adapter = new MyExpandableAdapter(parentItems, childItems, childContent);
				
				adapter.setInflater(((LayoutInflater)(getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE))), getActivity());
				
				expandableList.setAdapter(adapter);
//				expandableList.setOnChildClickListener(AmtFragment.this);

			}
			catch(Exception ex){
				Log.d("Error - AnnouncementFragment", ex.getMessage());
			}
			return rootView;
		}
		
		public void setGroupParents() {
			parentItems.add("COMP3111");
			parentItems.add("ELEC4410");
			parentItems.add("HUMA1102");
		}

		public void setChildData() {
			// COMP3111
			ArrayList<String> child = new ArrayList<String>();
			child.add("No labs in Week 1");
			child.add("Pop-up quiz on Feb 11");
			childItems.add(child);
						
			child = new ArrayList<String>();
			child.add("No labs in Week 1"
					+ "\n"
					+ "Posted Feb 3, 2014, 5:21 PM by JC Nam"
					+ "\n"
					+ "There are no labs in Week 1 (Feb. 4, Tue ~ Feb. 10, Mon) to sync lecture and tutorial schedules."
					+ "\n"
					+ "Please, note that each Week starts on every Tuesday and ends on Monday.");
			child.add("Pop-up quiz on Feb 11"
					+ "\n"
					+ "Posted Feb 5, 2014, 8:52 PM by Sung Kim"
					+ "\n"
					+ "Please come to class on time. We will have a quiz at the beginning of the class. Good luck!");
			childContent.add(child);
			
			// ELEC4410
			child = new ArrayList<String>();
			child.add("Midterm exam date and time");
			child.add("Project group");
			childItems.add(child);
			
			child = new ArrayList<String>();
			child.add("There are no rooms available on March 25. Therefore the midterm exam will be on 29 March (Saturday)  (2pm to 5pm)."
					+ "\n"
					+ "Let me know if you have a conflict on this date and time. If I do not hear from you by this Friday (February 7), the midterm exam date will be fixed."
					+ "\n"
					+ "There will not be a make-up exam for the students who cannot attend the midterm exam. If you have a conflict on March 29, you need to notify me now."
					+ "\n"
					+ "Prof. Kursun");
			child.add("It is to remind you that tomorrow (February 21) is the deadline to form project group.");
			childContent.add(child);
			
			// HUMA1102
			child = new ArrayList<String>();
			child.add("Self-Test 1");
			child.add("Self-Test 1 END in 15:00");
			child.add("Self-Test 2");
			childItems.add(child);
						
			child = new ArrayList<String>();
			child.add("Dear students,"
					+ "\n"
					+ "Self-test 1 begins at 15:00 today and will end at 15:00 on 27th Feb. Make sure you complete the self test and submit it on time. There is no later submission or make-ups for the self-tests."
					+ "\n"
					+ "Please keep in mind the following :"
					+ "\n"
					+ "1. Click on ‘Self-Test’ on the LMES menu and select the appropriate Test (Self-Test 1) to begin."
					+ "\n"
					+ "2. You should close other browsers when taking the Self-Test."
					+ "\n"
					+ "3. You should ensure a stable network connection (i.e. the network on campus) before taking the Self-Test. 4. You must click the ‘submit for grading’ button to complete the Self Test. (The ‘save for later’ button saves but DOES NOT submit your answers)."
					+ "\n"
					+ "5. After the Self-Test period ends, you will receive a confirmation page with a reference number and your score.  Please print a copy of this page for your records."
					+ "\n"
					+ "6. E-mail Rod Yu (roderickyu@ust.hk) BEFORE the close of the Self Test period for assistance if there is a problem with your submission."
					+ "\n"
					+ "7. No make-ups will be offered for Self-Tests!"
					+ "\n"
					+ "Regards,"
					+ "\n"
					+ "Rod");
			child.add("Dear students,"
					+ "\n"
					+ "Please make sure to submit your self-test before 15:00 today. There will not be any make-up after that. Please submit as soon as possible if you haven't."
					+ "\n"
					+ "Best,"
					+ "\n"
					+ "Rod");
			child.add("Dear students,"
					+ "\n"
					+ "Self-test 2 begins at 15:00 today and will end at 15:00 on 13th Mar. Make sure you complete the self test and submit it on time. There is no later submission or make-ups for the self-tests."
					+ "\n"
					+ "Please keep in mind the following :"
					+ "\n"
					+ "1. Click on ‘Self-Test’ on the LMES menu and select the appropriate Test (Self-Test 2) to begin."
					+ "\n"
					+ "2. You should close other browsers when taking the Self-Test."
					+ "\n"
					+ "3. You should ensure a stable network connection (i.e. the network on campus) before taking the Self-Test. 4. You must click the ‘submit for grading’ button to complete the Self Test. (The ‘save for later’ button saves but DOES NOT submit your answers)."
					+ "\n"
					+ "5. After the Self-Test period ends, you will receive a confirmation page with a reference number and your score.  Please print a copy of this page for your records."
					+ "\n"
					+ "6. E-mail Rod Yu (roderickyu@ust.hk) BEFORE the close of the Self Test period for assistance if there is a problem with your submission."
					+ "\n"
					+ "7. No make-ups will be offered for Self-Tests!"
					+ "\n"
					+ "Regards,"
					+ "\n"
					+ "Rod");
			childContent.add(child);
		}
	}

	
	public static class TdlFragment extends Fragment {
		public TdlFragment() {
			// Empty constructor required for fragment subclasses
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			View rootView = inflater.inflate(R.layout.fragment_todolist, container, false);
			provider = new TodoProvider(getActivity());
			taskView = (ListView) rootView.findViewById(R.id.tasklist);
			etNewTask = (EditText) rootView.findViewById(R.id.etNewTask);

			// dumb item deletion onclick
			taskView.setOnItemClickListener(new OnItemClickListener() {
			@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					id++;
					Log.d("Allen", String.valueOf(id));
					provider.deleteTask((int)id);
					renderTodos();
				}
			});
			try{
				renderTodos();
			}
			catch(Exception ex){
				Log.d("Error - TodolistFragment", ex.getMessage());
			}
			return rootView;
		}

		public void renderTodos() {
			List<String> todos = provider.findAll();
			// render the list
			taskView.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, todos
				.toArray(new String[] {})));
		}
	}

	public static class CFragment extends Fragment {
		public CFragment() {
			// Empty constructor required for fragment subclasses
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			View rootView = inflater.inflate(R.layout.fragment_course, container, false);
			TextView intro = (TextView) rootView.findViewById(R.id.intro);
		    intro.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvd3RaeEFZR1UxdEE/edit?usp=sharing>Introduction"));
		    intro.setMovementMethod(LinkMovementMethod.getInstance());
			TextView devProcess = (TextView) rootView.findViewById(R.id.devProcess);
			devProcess.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvSlV1Yk5MY1I3YmM/edit?usp=sharing>Development Process"));
			devProcess.setMovementMethod(LinkMovementMethod.getInstance());
			TextView ch1 = (TextView) rootView.findViewById(R.id.ch1);
			ch1.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvZGVFS05qdi13RnM/edit?usp=sharing>Chapter 1"));
			ch1.setMovementMethod(LinkMovementMethod.getInstance());
			TextView ch2 = (TextView) rootView.findViewById(R.id.ch2);
			ch2.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvVHR5VUZCTEVjWjg/edit?usp=sharing>Chapter 2"));
			ch2.setMovementMethod(LinkMovementMethod.getInstance());
			TextView ch3 = (TextView) rootView.findViewById(R.id.ch3);
			ch3.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvMFFrVDhfM0MyR00/edit?usp=sharing>Chapter 3"));
			ch3.setMovementMethod(LinkMovementMethod.getInstance());
			TextView baroque1 = (TextView) rootView.findViewById(R.id.baroque1);
			baroque1.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvT0pHdWtNRjZCRU0/edit?usp=sharing>Baroque I"));
			baroque1.setMovementMethod(LinkMovementMethod.getInstance());
			TextView baroque2 = (TextView) rootView.findViewById(R.id.baroque2);
			baroque2.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvOHFXdE1oMnFDOFU/edit?usp=sharing>Baroque II"));
			baroque2.setMovementMethod(LinkMovementMethod.getInstance());
			TextView baroque3 = (TextView) rootView.findViewById(R.id.baroque3);
			baroque3.setText(Html.fromHtml("<a href=https://drive.google.com/file/d/0B4GkI5BDsWpvbGJlNFNVSkRRQ00/edit?usp=sharing>Baroque III"));
			baroque3.setMovementMethod(LinkMovementMethod.getInstance());
		    
			try{

			}
			catch(Exception ex){
				Log.d("Error - CourseFragment", ex.getMessage());
			}
			return rootView;
		}

	}

	public void AmtBtn(View v){
		Fragment antF = new AmtFragment();
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.content_frame, antF).commit();
	}

	//onclick within @drawable/xml
	public void CalBtn(View v){
		Fragment calF = new CalFragment();
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.content_frame, calF).commit();
	}
	//onclick within @drawable/xml
	public void TdlBtn(View v){
		Fragment tdlF = new TdlFragment();
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.content_frame, tdlF).commit();
	}
	//onclick within @drawable/xml
	public void AddBtn(View v){
		provider.addTask(String.valueOf(etNewTask.getText()));
		renderTodos();
		etNewTask.setText("");
	}

	public void renderTodos() {
		List<String> todos = provider.findAll();
		// render the list
		taskView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todos
			.toArray(new String[] {})));
	}


}